import { useEffect,createContext,useState,useContext } from 'react';
const viewportContext = createContext({});

const ViewportProvider = ({ children }) => {
  // 监听浏览器宽高
  const [bodyWidth, setWidth] = useState(window.innerWidth);
  const [bodyHeight, setHeight] = useState(window.innerHeight);

  let timer = null;
  const handleWindowResize = () => {
    clearTimeout(timer);
    timer = setTimeout(()=>{
      setWidth(window.innerWidth);
      setHeight(window.innerHeight);
    },180)
  }

  useEffect(() => {
    window.addEventListener("resize", handleWindowResize);
    return () => window.removeEventListener("resize", handleWindowResize);
  }, []);

  return (
    <viewportContext.Provider value={{ bodyWidth, bodyHeight }}>
      {children}
    </viewportContext.Provider>
  );
};

export const useViewport = () => {
  const { bodyWidth, bodyHeight } = useContext(viewportContext);
  return { bodyWidth, bodyHeight };
}

export default ViewportProvider